<template>
  <!-- 计划维修表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '850px' : '1000px'"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="110"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划编码" prop="planCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planCode"
              placeholder="请输入计划编码"
              disabled
              clearable
            />

            <span v-else>{{ formData.planCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planName"
              placeholder="请输入计划名称"
              clearable
            />

            <span v-else>{{ formData.planName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维修类型" prop="repairType">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.repairType"
              placeholder="请选择维修类型"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('EamRepairType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "EamRepairType",
                formData.repairType
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维修负责人" prop="repariDirectorId">
            <SelectPerson-Member
              v-if="!props.isReadonly"
              :isMultiple="false"
              :maxCollapseTags="5"
              :showSelectPerson="showSelectPerson"
              @get-person="(id, object) => getDayPerson(id, object)"
              :width="'100%'"
            />
            <!--            <el-select-->
            <!--              style="width: 100%"-->
            <!--              v-if="!props.isReadonly"-->
            <!--              v-model="formData.repariDirectorId"-->
            <!--              placeholder="请选择维修负责人"-->
            <!--              clearable-->
            <!--              @change="changePerson"-->
            <!--            >-->
            <!--              <el-option-->
            <!--                v-for="item in personList"-->
            <!--                :label="`${item.firstName}`"-->
            <!--                :value="`${item.id}`"-->
            <!--              />-->
            <!--            </el-select>-->

            <span v-else>{{ formData.repairManagerName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="planStartTime">
            <el-date-picker
              style="width: 500px"
              v-if="!props.isReadonly"
              v-model="formData.planStartTime"
              type="date"
              placeholder="请输入计划开始时间"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              @change="handlePlanStartDate"
            />
            <span v-else>{{ formData.planStartTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划结束日期" prop="planEndTime">
            <el-date-picker
              style="width: 500px"
              v-if="!props.isReadonly"
              v-model="formData.planEndTime"
              type="date"
              placeholder="请输入计划结束日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
            <span v-else>{{ formData.planEndTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备管理部门" prop="deviceDepartment">
            <SelectOriganizationDangerGrant
              v-if="!props.isReadonly"
              @change="(ids:string) => getSelectIds(ids, '管理部门')"
              @change-data="(datas) => getSelectDatas(datas, '管理部门')"
              :isCheckStrictly="true"
              :isMultiple="false"
              :disabled="false"
              :data="dataObject('管理部门')"
              :selectData="formData.deviceDepartment"
            />
            <span v-else>{{ formData.deviceDepartment }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="提醒时间" prop="planRemindTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planRemindTime"
              placeholder="请输入提醒时间"
              clearable
            >
              <template #append>
                <el-select
                  v-model="formData.planRemindTimeType"
                  placeholder="单位"
                  style="width: 85px"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'reminderTime'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-input>

            <span v-else
              >{{ formData.planRemindTime
              }}{{ formData.planRemindTimeType }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维修执行部门" prop="repairDepartment">
            <SelectOriganizationDangerGrant
              v-if="!props.isReadonly"
              @change="(ids:string) => getSelectIds(ids, '维修执行部门')"
              @change-data="(datas) => getSelectDatas(datas, '维修执行部门')"
              :isCheckStrictly="true"
              :isMultiple="false"
              :disabled="false"
              :data="dataObject('管维修执行')"
              :selectData="formData.repairDepartment"
            />
            <span v-else>{{ formData.repairDepartment }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <template v-if="!props.isReadonly">
              <el-radio-group v-model="formData.enabled">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
            <span v-else>{{
              dictionaryStore.filterDictName("YesNo", formData.enabled)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划编码</div>
        </template>
        {{ formData.planCode }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.planName || "暂无备注" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">维修类型</div>
        </template>
        {{
          dictionaryStore.filterDictName("EamRepairType", formData.repairType)
        }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">维修负责人</div>
        </template>
        {{ formData.repariDirectorName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划开始日期</div>
        </template>
        {{
          formData.planStartTime
            ? dayjs(formData.planStartTime).format("YYYY-MM-DD")
            : ""
        }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划结束时间</div>
        </template>
        {{
          formData.planEndTime
            ? dayjs(formData.planEndTime).format("YYYY-MM-DD")
            : ""
        }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划状态</div>
        </template>
        {{ useDictionary("RepairPlanStatus", formData.planStatus) }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <el-tag v-if="formData.enabled === 1" type="">启用</el-tag>
        <el-tag v-else type="info">停用</el-tag>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备管理部门</div>
        </template>
        {{ formData.deviceDepartmentName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">提醒时间</div>
        </template>
        {{ formData.planRemindTime }}
        {{
          dictionaryStore.filterDictName(
            "reminderTime",
            formData.planRemindTimeType
          )
        }}
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">维修执行部门</div>
        </template>
        {{ formData.repairDepartmentName }}
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "暂无备注" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>

    <div
      style="display: flex; justify-content: space-between; align-items: center"
      v-show="props.isReadonly"
    >
      <h4 class="mb-[20px] mt-[20px]">计划明细</h4>
    </div>
    <el-table
      v-show="props.isReadonly"
      ref="dataTableRef"
      v-loading="loading"
      :data="tableData"
      highlight-current-row
      border
    >
      <el-table-column type="index" width="55" align="center" />

      <el-table-column
        label="设备编码"
        prop="assetCode"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="设备名称"
        prop="assetName"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="设备种类"
        prop="assetTypeName"
        min-width="100"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        label="品牌型号"
        prop="assetBrandName"
        min-width="150"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ scope.row.assetModelNo }}{{ scope.row.assetModelNo ? "-" : ""
          }}{{ scope.row.assetBrandName }}
        </template>
      </el-table-column>
      <el-table-column
        label="维修类型"
        prop="repairType"
        min-width="100"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ useDictionary("PlanRepairType", scope.row.repairType) }}
        </template>
      </el-table-column>
      <el-table-column
        label="维修班组"
        prop="executeTeamName"
        min-width="100"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        label="维修人员"
        prop="executeUsers"
        min-width="150"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ scope.row.executeUsers?.map((item) => item.personName).join(",") }}
        </template>
      </el-table-column>
      <el-table-column
        label="设备位置"
        prop="locationName"
        min-width="100"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        label="计划维修内容"
        prop="remarks"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="计划开始时间"
        prop="planStartTime"
        min-width="150"
        show-overflow-tooltip
        align="center"
      />
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";
import { useDictionary } from "../../../../../utils/useTable";
import { ref } from "vue";
defineOptions({
  name: "COMMONREPAIRPLANADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
const rules = reactive({
  version: [],
  // planCode: [
  //   { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  // ],
  planName: [
    { required: true, message: "请输入计划名称", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repairType: [
    { required: true, message: "请选择维修类型", trigger: "change" },
  ],
  repariDirectorId: [
    { required: true, message: "请选择维修负责人", trigger: "change" },
  ],
  planStartTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
    { validator: validateStartTime, trigger: "change" },
  ],
  planEndTime: [
    { required: true, message: "请选择计划结束时间", trigger: "change" },
    { validator: validateEndTime, trigger: "change" },
  ],
  planRemindTime: [
    {
      required: true,
      message: "请输入0~100的数字",
      trigger: "blur",
      pattern: /^([0-9][0-9]?|100)$/,
    },
  ],
  planRemindTimeType: [
    { required: true, message: "请选择维修类型", trigger: "change" },
  ],
  deviceDepartment: [
    { required: true, message: "请选择设备管理部门", trigger: "change" },
  ],
  repairDepartment: [
    { required: true, message: "请选择维修执行部门", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});
// 校验
function validateEndTime(rule, value, callback) {
  if (formData.planStartTime && value < formData.planStartTime) {
    callback(new Error("结束日期不能小于开始日期"));
  } else {
    callback();
  }
}
// 校验
function validateStartTime(rule, value, callback) {
  if (formData.planEndTime && value > formData.planEndTime) {
    callback(new Error("开始日期不能大于结束日期"));
  } else {
    callback();
  }
}
const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  planCode: "",
  planName: "",
  repairType: "",
  repariDirectorId: "",
  repariDirectorName: "",
  planStartTime: "",
  planEndTime: "",
  planRemindTime: "",
  planRemindTimeType: "0",
  deviceDepartment: "",
  deviceDepartmentName: "",
  repairDepartment: "",
  repairDepartmentName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  planStatus: "",
  enabled: 1,
  deleted: "",
  assetKind: props.assetKind,
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        planCode,
        planName,
        repairType,
        repariDirectorId,
        repariDirectorName,
        planStartTime,
        planEndTime,
        planRemindTime,
        planRemindTimeType,
        deviceDepartment,
        deviceDepartmentName,
        repairDepartment,
        repairDepartmentName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        planStatus,
        deleted,
        assetKind,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        planCode,
        planName,
        repairType,
        repariDirectorId,
        repariDirectorName,
        planStartTime,
        planEndTime,
        planRemindTime,
        planRemindTimeType,
        deviceDepartment,
        deviceDepartmentName,
        repairDepartment,
        repairDepartmentName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        planStatus,
        deleted,
        assetKind,
      });
      showSelectPerson.value = [
        {
          id: repariDirectorId,
          personName: repariDirectorName,
        },
      ];
      getTableList(id, assetKind);
    } else {
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.planCode = "";
  formData.planName = "";
  formData.repairType = "";
  formData.repariDirectorId = "";
  formData.repariDirectorName = "";
  formData.planStartTime = "";
  formData.planEndTime = "";
  formData.planRemindTime = "";
  formData.planRemindTimeType = "0";
  formData.deviceDepartment = "";
  formData.deviceDepartmentName = "";
  formData.repairDepartment = "";
  formData.repairDepartmentName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.assetKind = props.assetKind;
  showSelectPerson.value = [];
}

const loading = ref(false);

/** 计划维修保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/equrepairplan/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "管理部门") {
    formData.deviceDepartment = ids;
  }
  if (item == "维修执行部门") {
    formData.repairDepartment = ids;
  }
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, item: any) {
  if (item == "管理部门") {
    formData.deviceDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
  if (item == "维修执行部门") {
    formData.repairDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
}
// 组织机构 placeholder值
const dataObject = (item: string) => {
  return {
    name: item == "管理部门" ? "管理部门" : "维修执行部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 人员改变时
const changePerson = (e: any) => {
  if (e) {
    personList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.repariDirectorName = item.firstName;
      }
    });
  } else {
    formData.repariDirectorId = "";
    formData.repariDirectorName = "";
  }
};

const personList = ref([]);
const getPersonList = async () => {
  const res = await request({
    url: "/system/sysUser/getList",
    method: "post",
    data: {},
  });
  personList.value = res.data;
};
onMounted(async () => {
  await getPersonList();
});
const tableData = ref([]);

const getTableList = async (planId, assetKind) => {
  const { data } = await request({
    url: "/eam/eamrepairplandetail/getList",
    method: "post",
    data: { planId, assetKind },
  });
  tableData.value = data;
};
const handlePlanStartDate = async () => {
  const { data } = await request({
    url: "/eam/mouldrepairplan/getPlanNoByStartDate",
    method: "get",
    params: {
      planStartDate: formData.planStartTime,
      assetKind: props.assetKind,
    },
  });
  formData.planCode = data;
};

const showSelectPerson = ref([]);

function getDayPerson(Ids: string[], Objects: any) {
  if (Ids && Objects) {
    console.log(Ids, Objects);
    formData.repariDirectorId = Objects[0].id;
    formData.repariDirectorName = Objects[0].personName;
    showSelectPerson.value = [
      {
        id: Objects[0].id,
        personName: Objects[0].personName,
      },
    ];
  } else {
    formData.repariDirectorId = "";
    formData.repariDirectorName = "";
    showSelectPerson.value = [];
  }
  console.log(formData.repariDirectorId, formData.repariDirectorName);
}
</script>

<style scoped lang="scss">
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 160px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
